﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace VideoCache.Security.Implements
{
    public class DesProvider : ISecurityProvider
    {
        public string Encrypt(string code)
        {
            // 密钥
            string key = Guid.NewGuid().ToString("N").Substring(0, 8);

            byte[] inputByteArray = Encoding.UTF8.GetBytes(code);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            des.Key = Encoding.ASCII.GetBytes(key);
            des.Mode = CipherMode.ECB;
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();

                    return Convert.ToBase64String(mStream.ToArray()) + "." + key;
                }
            }
        }

        public string Decrypt(string code)
        {
            string key = code.Substring(code.LastIndexOf(".") + 1);
            string encryptString = code.Substring(0, code.LastIndexOf("."));

            byte[] inputByteArray = Convert.FromBase64String(encryptString);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            des.Key = Encoding.UTF8.GetBytes(key);
            des.Mode = CipherMode.ECB;
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();
                    return Encoding.UTF8.GetString(mStream.ToArray());
                }
            }
        }
    }
}